import { Form, Input, Drawer, Button, Upload, message, Pagination } from "antd";
import RcViewer from "@hanyk/rc-viewer";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import React, { useState, useEffect } from "react";
import CardCoverItem from "../../CardCoverItem";
import { list, getFileNameUUID, put, signatureUrl } from "../../../utils/oss";
import { positionStyle } from "./SettingArticle";
export default function OssFileDrawer({
  visible,
  closeOssFileVisible,
  handlerDataInfo = () => {
    console.log("没传参数,呆逼");
  },
  handlerClickCard = (info) => {
    closeOssFileVisible();
    handlerDataInfo(info, "cover");
  },
}) {
  const [fileList, setFileList] = useState([]);
  const [fileName, setFileName] = useState("");
  const [fileType, setFileType] = useState("");
  const [pIndex, setPageIndex] = useState(1);
  const [pSize, setPageSize] = useState(8);
  const [total, setTotal] = useState(0);
  const [handlerData, setHandlerData] = useState([]);
  useEffect(() => {
    init();
  }, []);
  const init = () => {
    getOssFileList();
  };
  //获取数据
  const getOssFileList = async (pageIndex = 1, pageSize = 8) => {
    NProgress.start();
    let { objects } = await list();
    setHandlerData([...objects]);
    setTotal(objects.length);
    objects = objects.map((item) => {
      return {
        ...item,
        fileType: item.name.split(".")[1],
      };
    });
    objects = objects.filter((item) => {
      return item.name.includes(fileName) && item.fileType.includes(fileType);
    });
    objects.sort((a, b) => {
      return new Date(b.lastModified) - new Date(a.lastModified);
    });
    objects = objects.slice((pageIndex - 1) * pageSize, pageSize * pageIndex);
    await setFileList([...objects]);
    NProgress.done();
  };
  const handlerFileList = async (pageIndex = 1, pageSize = 8) => {
    let newList = JSON.parse(JSON.stringify(handlerData));
    newList = newList.map((item) => {
      return {
        ...item,
        fileType: item.name.split(".")[1],
      };
    });
    newList = newList.filter((item) => {
      return item.name.includes(fileName) && item.fileType.includes(fileType);
    });
    setTotal(newList.length);
    newList.sort((a, b) => {
      return new Date(b.lastModified) - new Date(a.lastModified);
    });
    newList = newList.slice((pageIndex - 1) * pageSize, pageSize * pageIndex);
    await setFileList([...newList]);
  };
  const changePagination = (pageIndex, pageSize) => {
    setPageSize(pageSize);
    setPageIndex(pageIndex);
    handlerFileList(pageIndex, pageSize);
  };
  //重置
  const resetForm = () => {
    setFileName("");
    setFileType("");
  };
  return (
    <Drawer
      title="文件选择"
      extra={<i className="iconfont icon-chahao" onClick={closeOssFileVisible}></i>}
      visible={visible}
      size="large"
      onClose={closeOssFileVisible}
      closable={false}
    >
      <HeaderFormCom
        getOssFileList={getOssFileList}
        handlerSearchBtn={() => {
          setPageIndex(1);
          handlerFileList(1, pSize);
        }}
        handlerResetBtn={resetForm}
        isShowUpload
      >
        <Form layout="inline">
          <Form.Item label="文件名">
            <Input
              placeholder="请输入文件名"
              value={fileName}
              onChange={(e) => {
                setFileName(e.target.value);
              }}
            />
          </Form.Item>
          <Form.Item label="文件类型">
            <Input
              placeholder="请输入文件类型"
              value={fileType}
              onChange={(e) => {
                setFileType(e.target.value);
              }}
            />
          </Form.Item>
        </Form>
      </HeaderFormCom>
      <RcViewer>
        <div className="oss-file-wrapper">
          {fileList.map((item, index) => (
            <CardCoverItem
              info={item}
              key={index}
              cover={<img src={item.url} />}
              title={item.name.split("flieName/")[1]}
              handlerInfoClick={handlerClickCard}
              handlerType="url"
              isClickImg={false}
            ></CardCoverItem>
          ))}
        </div>
      </RcViewer>
      <div className="oss-file-pagination">
        <PaginationCom total={total} pageSize={pSize} pageIndex={pIndex} onChange={changePagination} style={positionStyle} />
      </div>
    </Drawer>
  );
}

export const HeaderFormCom = ({ handlerSearchBtn, handlerResetBtn, getOssFileList, isShowUpload = false, ...props }) => {
  const handleUpload = async (option) => {
    NProgress.start();
    // // 获取文件的后缀名
    var obj = option.file.name;
    var index = obj.lastIndexOf(".");
    obj = obj.substring(index, obj.length);
    // 生成的文件名，保留文件后缀名，进行拼接
    let objName = getFileNameUUID() + option.file.name;
    // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
    await put(`flieName/${objName}`, option.file).then(() => {
      // console.log(res);
      message.success("上传成功");
      // 上传成功之后，转换真实的地址
      signatureUrl(`flieName/${objName}`).then((res) => {
        // console.log(res);
      });
    });
    await NProgress.done();
    getOssFileList();
  };
  return (
    <>
      {props.children}
      <div className="handler_box">
        <Button type="primary" onClick={handlerSearchBtn}>
          搜索
        </Button>
        <Button onClick={handlerResetBtn}>重置</Button>
      </div>
      {isShowUpload ? (
        <div className="handler_box">
          <OssUploadCom handleUpload={handleUpload}>
            <Button>上传文件</Button>
          </OssUploadCom>
        </div>
      ) : (
        ""
      )}
    </>
  );
};
//分页
export const PaginationCom = ({ total, pageSize = 8, pageIndex = 1, onChange, style }) => {
  return (
    <Pagination
      style={style}
      total={total}
      showTotal={(total) => `共 ${total} 条`}
      pageSize={pageSize}
      current={pageIndex}
      pageSizeOptions={[8, 16, 24, 36]}
      onChange={onChange}
      showTitle={false}
    />
  );
};

export const OssUploadCom = ({
  handleUpload = async (option) => {
    NProgress.start();
    // // 获取文件的后缀名
    var obj = option.file.name;
    var index = obj.lastIndexOf(".");
    obj = obj.substring(index, obj.length);
    // 生成的文件名，保留文件后缀名，进行拼接
    let objName = getFileNameUUID() + option.file.name;
    // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
    await put(`flieName/${objName}`, option.file).then(() => {
      // console.log(res);
      message.success("上传成功");
      // 上传成功之后，转换真实的地址
      signatureUrl(`flieName/${objName}`).then((res) => {
        // console.log(res);
      });
    });
    await NProgress.done();
  },
  showUploadList = false,
  ...props
}) => {
  return (
    <Upload action customRequest={handleUpload} showUploadList={showUploadList}>
      {props.children}
    </Upload>
  );
};
